// 导入axios HTTP客户端
import axios from "axios";
import { useAuthStore } from "@/stores/auth";
// 定义HTTP请求工具类
class Http {
  constructor() {
    // 创建axios实例并配置默认值
    this.instance = axios.create({
      baseURL: import.meta.env.VITE_BASE_URL, // 基础URL，从环境变量获取
      timeout: 6000, // 请求超时时间，单位毫秒
      headers: {}, // 自定义请求头
    });
    this.instance.interceptors.request.use((config) => {
      // 在请求发送之前做些什么
      const authStore = useAuthStore();
      // 如果用户已登录，则在请求头中添加令牌
      if (authStore.is_login) {
        config.headers.Authorization = `JWT ${authStore.token}`;
      }
      return config;
    });
  }

  // POST请求方法
  post(path, data) {
    // 返回Promise对象，处理请求结果
    return new Promise(async (resolve, reject) => {
      try {
        // 发送POST请求
        console.log(path, data);
        let result = await this.instance.post(path, data);
        // 成功时返回响应数据
        resolve(result.data);
      } catch (err) {
        // 失败时返回错误详情
        let detail = err.response.data.detail;
        reject(detail);
      }
    });
  }

  // GET请求方法
  get(path, params) {
    return new Promise(async (resolve, reject) => {
      try {
        let result = await this.instance.get(path, { params });
        resolve(result.data);
      } catch (err) {
        let detail = err.response.data.detail;
        reject(detail);
      }
    });
  }

  put(path, data) {
    // 返回Promise对象，处理请求结果
    return new Promise(async (resolve, reject) => {
      try {
        // 发送POST请求
        let result = await this.instance.put(path, data);
        // 成功时返回响应数据
        resolve(result.data);
      } catch (err) {
        // 失败时返回错误详情
        try {
          let detail = err.response.data.detail;
          reject(detail);
        } catch {
          reject("服务器错误");
        }
      }
    });
  }
  delete(path) {
    return new Promise(async (resolve, reject) => {
      try {
        // 发送POST请求
        let result = await this.instance.delete(path);
        // 成功时返回响应数据
        resolve(result);
      } catch (err) {
        // 失败时返回错误详情
        let detail = err.response.data.detail;
        reject(detail);
      }
    });
  }
  downloadFile(path, params){
    return new Promise(async (resolve, reject) => {
        try{
            let result = await this.instance.get(path, {
                params,
                responseType: "blob"
            })
            resolve(result)
        }catch(err){
            let detail = err.response.data.detail;
            reject(detail)
        }
    })
}
}

// 导出HTTP工具类的实例
export default new Http();
